<template>
  <div>
    <!-- 头部 -->
    <Top />

    <p class="header">注册用户</p>
    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="phone"
        name="手机号"
        label="手机号"
        placeholder="手机号"
        :rules="[
          { required: true, message: '请填写手机号' },
          { pattern, message: '手机号格式错误' },
        ]"
      />
      <div class="vertify">
        <van-field
          v-model="code"
          name="验证码"
          label="验证码"
          placeholder="验证码"
          :rules="[{ required: true, message: '请填写验证码' }]"
        />
        <van-button
          native-type="button"
          type="primary"
          size="small"
          @click="getCode"
          >获取验证码</van-button
        >
      </div>

      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        v-model="password2"
        type="password"
        name="确认密码"
        label="确认密码"
        placeholder="确认密码"
        :rules="[
          { required: true, message: '请填写确认密码' },
          { validator, message: '两次输入的密码不一致' },
        ]"
      />

      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>

    <div class="footer">

    <van-button  plain type="warning" @click="goLogin" size="small">已有账号？去登录</van-button>
</div>
  </div>
</template>

<script>
import { Notify } from "vant";
import { mapState } from "vuex";
export default {
  name: "Register",
  data() {
    return {
      phone: "",
      password: "",
      password2: "",
      code: "",
      pattern: /^1{1}\d{10}$/,
    };
  },
  watch: {},
  computed: {},
  methods: {
    async onSubmit(values) {
      // console.log("submit", values);
      let { phone, password, code } = this;
      try {
        let res = await this.$store.dispatch("register", { phone, password, code });
        Notify({ type: "success", message: '恭喜大哥，注册成功'});
        this.$router.push("/login");
      } catch (error) {
        // console.log(error);
        
        Notify({ type: "warning", message: error });
      }
    },

    //确认密码的验证规则
    validator() {
      return this.password2 == this.password;
    },
  goLogin(){
    this.$router.push('/login')
  },
    //获取验证码
    async getCode() {
      if (!this.phone) {
        Notify({ type: "warning", message: "请填写手机号" });
        return;
      }
      try {
        let res = await this.$store.dispatch("getCode", parseInt(this.phone));
        this.code = res;
      } catch (error) {}
    },
  },
};
</script>

<style lang="less" scoped>
.header {
  text-align: center;
  // color: red;
  font-weight: 700;
}
.vertify {
  display: flex;
  button {
    width: 100px;
  }
}
.footer{
  display: flex;
  justify-content: center;
  padding-top:80px;
}
</style>